package org.taobao.ibatiside.ui.util;

import java.io.IOException;
import java.util.Iterator;

import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.taobao.ibatiside.model.configv2.Configv2Factory;
import org.taobao.ibatiside.model.configv2.DocumentRoot;
import org.taobao.ibatiside.model.configv2.SqlMapConfigType;
import org.taobao.ibatiside.model.configv2.SqlMapType;
import org.taobao.ibatiside.model.configv2.util.Configv2XMLProcessor;

public class Config2XMLProcessor extends Configv2XMLProcessor {
	public void addSqlMap(IFile configFile, String map){
		if (StringUtils.isBlank(map)) return;
		Resource resource = createResourceSet().getResource(URI.createPlatformResourceURI(configFile.getFullPath().toString(),false),true);
		SqlMapConfigType smt = ((DocumentRoot)resource.getContents().get(0)).getSqlMapConfig();
		insert(map,smt);
		try {
			resource.save(null);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public void removeSqlMap(IFile configFile, String map){
		if (StringUtils.isBlank(map)) return;
		Resource resource = createResourceSet().getResource(URI.createPlatformResourceURI(configFile.getFullPath().toString(),false),true);
		SqlMapConfigType smt = ((DocumentRoot)resource.getContents().get(0)).getSqlMapConfig();
		remove(map, smt);
		try {
			resource.save(null);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void remove(String map, SqlMapConfigType smt) {
		for (Iterator ite = smt.getSqlMap().iterator(); ite.hasNext();){
			SqlMapType st = (SqlMapType) ite.next();
			if (map.equals(st.getResource())){
				ite.remove();
				break;
			}
		}
	}
	private void insert(String map, SqlMapConfigType smt) {
		EList<SqlMapType> all_sqlmap = smt.getSqlMap();	
		for (SqlMapType file: all_sqlmap){
			if (map.equals(file.getResource())){
				return;
			}
		}
		SqlMapType new_file = Configv2Factory.eINSTANCE.createSqlMapType();
		new_file.setResource(map);
		smt.getSqlMap().add(new_file);
	}
}
